package pkg.genericity.controllers;

import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MainController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String beanPackage, errorPage, viewNamePattern;
       
    public MainController() {
        super();
        
        ResourceBundle bundle= ResourceBundle.getBundle("pkg.genericity.app");
        beanPackage= bundle.getString("data.objects.package");
        errorPage= bundle.getString("error.page");
        viewNamePattern= bundle.getString("view.name.pattern");
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String bean = request.getParameter("bean");
		String viewType = request.getParameter("viewtype");
		try {
			if(bean== null) {
				throw new ClassNotFoundException("Bean parameter in request is null");
			}
			Class.forName(beanPackage+"."+bean);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			request.getSession().setAttribute("errmsg", "Bean with name "+bean+" Not found");
			request.getSession().setAttribute("nexturl", "");
			response.sendRedirect(errorPage);
			return;
		}	
			request.getSession().setAttribute("beanclass", beanPackage+"."+bean);
			request.setAttribute("title", bean+" information "+viewType+" page");
			request.getRequestDispatcher(viewNamePattern.replace("$(viewname)", viewType)).forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
